<template>
  <div class="app-container">
    <el-container>
      <el-aside width="200px" style="background-color: #fff;padding: 0">
        <el-tree
          class="tree-border"
          :data="treeOptions"
          :show-checkbox=false
          :expand-on-click-node=false
          :check-on-click-node=true
          :highlight-current=true
          default-expand-all
          ref="tree"
          node-key="id"
          :props="defaultProps"
          @node-click="handleNodeClick"
        ></el-tree>
      </el-aside>
      <el-main>
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="68px">
          <el-form-item label="材料名称" prop="materiaId">
            <el-input
              v-model="queryParams.materiaName"
              placeholder="请输入材料名称"
              clearable
            />
          </el-form-item>
          <el-form-item label="项目" prop="projectId">
            <el-select v-model="queryParams.projectId"
                       placeholder="请选择项目"
                       clearable>
              <el-option v-for="item in projectList" :key="item.projectId" :label="item.projectName"
                         :value="item.projectId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['material:materialPurchase:add']"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['material:materialPurchase:edit']"
            >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['material:materialPurchase:remove']"
            >删除
            </el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="materialPurchaseList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="材料名称" align="center" prop="materiaName"/>
          <el-table-column label="材料规格" align="center" prop="materiaStandard"/>
          <el-table-column label="供应商" align="center" prop="supplierName"/>
          <el-table-column label="采购时间" align="center" prop="purchaseDatetime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.purchaseDatetime, '{y}/{m}/{d} ') }}</span>
              <span>{{ new Date(scope.row.purchaseDatetime).getHours() < 12 ? '上午' : '下午' }}</span>
              <span>{{ parseTime(scope.row.purchaseDatetime, '{h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="计划到场时间" align="center" prop="planDate" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.planDate, '{y}/{m}/{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="计划到场" align="center" prop="planQuantity"/>
          <el-table-column label="已到场" align="center" prop="alreadyQuantity"/>
          <el-table-column label="状态" align="center" prop="status" width="110">
            <template slot-scope="scope">
              <el-tag v-if="!isNaN(parseFloat(scope.row.status))" type="primary">已到场{{ scope.row.status }}%</el-tag>
              <el-tag v-else-if="scope.row.status === '未下单'" type="warning">未下单</el-tag>
              <el-tag v-else-if="scope.row.status === '下单中'" type="warning">下单中</el-tag>
              <el-tag v-else-if="scope.row.status === '生产中'" type="warning">生产中</el-tag>
              <el-tag v-else-if="scope.row.status === '已到场'" type="success">已到场</el-tag>
              <el-tag v-else-if="scope.row.status === '运输中'" type="warning">运输中</el-tag>
              <el-tag v-else type="info">{{ scope.row.status }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['material:materialPurchase:edit']"
              >修改
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['material:materialPurchase:remove']"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

        <!-- 添加或修改材料采购记录对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
          <el-form ref="form" :model="form"  :rules="rules" label-width="120px">
            <el-form-item label="项目 " >
              <el-input v-model="form.projectName" placeholder="请选择材料" disabled readonly/>
            </el-form-item>
            <el-form-item label="材料类型" >
              <el-cascader :options="cascaderData"
                           :props="cascaderDataProps"
                           v-model="form.materiatypeId"
                           @change="cascaderChange"
                           :show-all-levels="false"
                           :disabled="formSelect"
              >
              </el-cascader>
            </el-form-item>
            <el-form-item label="材料" prop="materiaId">
              <el-select v-model="form.materiaId"
                         placeholder="请选择材料"
                         @change="materiaChange"
                         :disabled="formSelect"
                         clearable>
                <el-option v-for="item in materiaSelectListByTypeId"
                           :key="item.materiaId"
                           :label="item.materiaName"
                           :value="item.materiaId">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="供应商" prop="supplierId">
              <el-select v-model="form.supplierId"
                         placeholder="请选择供应商"
                         clearable>
                <el-option v-for="item in supplierList"
                           :key="item.supplierId"
                           :label="item.supplierName"
                           :value="item.supplierId">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="计划到场" prop="planQuantity">
              <el-input-number :min="0"  v-model="form.planQuantity" placeholder="请输入计划到场">

              </el-input-number>
            </el-form-item>
            <el-form-item label="已到场" prop="alreadyQuantity">
              <el-input-number :min="0" :max="form.planQuantity" v-model="form.alreadyQuantity" placeholder="请输入已到场">

              </el-input-number>
            </el-form-item>
            <el-form-item label="计划到场时间" prop="planDate">
              <el-date-picker clearable
                              v-model="form.planDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择计划到场时间">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-input v-model="form.status" placeholder="请输入状态,纯数字代表百分比,其余以文字描述状态"/>
            </el-form-item>
            <el-form-item label="负责人" prop="reponsibleName">
              <el-input v-model="form.reponsibleName" placeholder="请输入负责人"/>
            </el-form-item>
            <el-form-item label="电话" prop="reponsibleTel">
              <el-input v-model="form.reponsibleTel" placeholder="请输入电话"/>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input :rows="2" v-model="form.remark" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
      </el-main>
    </el-container>

  </div>
</template>

<script>
import {
  listMaterialPurchase,
  getMaterialPurchase,
  delMaterialPurchase,
  addMaterialPurchase,
  updateMaterialPurchase
} from "@/api/material/materialPurchase";
import {getTreeData} from "@/api/material/materialType";
import {listProjectByUserId} from "@/api/project/project";
import {listMaterialByTypeId} from "@/api/material/material";
import {listSupplierAll} from "@/api/material/supplier";

export default {
  name: "MaterialPurchase",
  data() {
    return {
      // 表单选项
      formSelect:false,
      // 项目列表的数组
      projectList: [],
      // 供应商列表的数组
      supplierList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 材料采购记录表格数据
      materialPurchaseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 树选项
      treeOptions: [],
      // 树属性
      defaultProps: {
        label: 'materiatypeName',
        children: 'children'
      },
      //级联选项
      cascaderData: [],
      //材料列表
      materialList: [],
      //材料表单列表
      materiaSelectListByTypeId: [],
      //级联属性
      cascaderDataProps: {
        value: 'materiatypeId',
        label: 'materiatypeName',
        children: 'children',
        emitPath: "false"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        materiaId: null,
        projectId: null,
        reponsibleTel: null
      },
      // 表单参数
      form: {
        materiaId: null,
        supplierId: null,
        projectId: null,
        status: null,
        remark: null,
        reponsibleName: null,
        reponsibleTel: null
      },
      // 表单校验
      rules: {
        materiaId: [
          { required: true, message: "材料不能为空", trigger: "blur" }
        ],
        supplierId: [
          { required: true, message: "供应商不能为空", trigger: "blur" }
        ],
        projectId: [
          { required: true, message: "项目不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "blur" },
          //长度不超过50
          { max: 50, message: "状态长度不超过50", trigger: "blur" }
        ],
        // 备注 不为空,不超过200
        remark: [
          { required: true, message: "备注不能为空", trigger: "blur" },
          //长度不超过200
          { max: 200, message: "备注长度不超过200", trigger: "blur" }
        ],
        reponsibleName: [
          { required: true, message: "负责人不能为空", trigger: "blur" }
        ],
        reponsibleTel: [
          { required: true, message: "电话不能为空", trigger: "blur" },
          //长度不超过11
          { max: 11, message: "电话长度不超过11", trigger: "blur" },
          //正则表达式验证
          { pattern: /^1[3456789]\d{9}$/, message: "请输入正确的手机号", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getTypeTree();
    this.getListProject();
    this.getListSupplier();
  },
  methods: {
    /** 级联选择器改变 */
    cascaderChange(value) {
      console.log(value);
      this.form.materiatypeId = value[value.length - 1];
      this.materiaSelectListByTypeId=null;
      this.form.materiaId = null;
      /** 查询材料列表 */
      listMaterialByTypeId(this.form.materiatypeId).then(response => {
        this.materiaSelectListByTypeId = response.data;
      })
    },
    /** 材料改变 */
    materiaChange(value) {
      this.form.materiaId = value;
      this.form.projectName = null;
      this.form.projectId = null;
      if (value){
        let materias = this.materiaSelectListByTypeId
          .filter(item => {
            return item.materiaId == value
          })
        console.log(materias);
        this.form.projectName = materias[0].projectName;
        this.form.projectId = materias[0].projectId;
      }
    },
    /** 用户能看见的项目列表 */
    getListProject() {
      listProjectByUserId().then(response => {
        this.projectList = response.data;
      });
    },
    /** 查询供应商列表 */
    getListSupplier() {
      listSupplierAll().then(response => {
        this.supplierList = response.data;
      });
    },
    /** 查询材料采购记录列表 */
    getList() {
      this.loading = true;
      listMaterialPurchase(this.queryParams).then(response => {
        this.materialPurchaseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 获取材料类型树
    getTypeTree() {
      getTreeData().then(res => {
        this.treeOptions = [res.data];

        this.cascaderData = this.handleTreeList(this.treeOptions)
        console.log(this.cascaderData);
      })
    },
    handleTreeList(list) { // 删除第三级children
      for (let i = 0; i < list.length; i++) {
        if (list[i].children.length < 1) {				// 判断children的数组长度
          list[i].children = undefined
        } else {
          this.handleTreeList(list[i].children)
        }
      }
      return list
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        purchaseRecordId: null,
        materiaId: null,
        supplierId: null,
        projectId: null,
        planDate: null,
        planQuantity: null,
        alreadyQuantity: null,
        status: null,
        purchaseDatetime: null,
        remark: null,
        reponsibleName: null,
        reponsibleTel: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.purchaseRecordId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.formSelect=false
      this.open = true;
      if (this.queryParams.materiatypeId) {
        //已经选择了材料类型
        this.form.materiatypeId = this.queryParams.materiatypeId;
        listMaterialByTypeId(this.form.materiatypeId).then(response => {
          this.materiaSelectListByTypeId = response.data;
        })
      }
      this.title = "添加材料采购记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.formSelect=true
      this.reset();
      const purchaseRecordId = row.purchaseRecordId || this.ids
      getMaterialPurchase(purchaseRecordId).then(response => {
        this.form = response.data;
        this.form.planQuantity =Number(this.form.planQuantity)
        this.open = true;
        this.title = "修改材料采购记录";
      }).then(res => {
        /** 查询材料列表 */
        listMaterialByTypeId(this.form.materiatypeId).then(response => {
          this.materiaSelectListByTypeId = response.data;
        })
      })

    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.purchaseRecordId != null) {
            updateMaterialPurchase(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMaterialPurchase(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.queryParams.projectId = this.form.projectId;
              this.queryParams.materiatypeId = this.form.materiatypeId;
              this.queryParams.materiatypePid = null;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const purchaseRecordIds = row.purchaseRecordId || this.ids;
      this.$modal.confirm('是否确认删除材料采购记录编号为"' + purchaseRecordIds + '"的数据项？').then(function () {
        return delMaterialPurchase(purchaseRecordIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    handleNodeClick(data) {
      console.log(data);
      this.queryParams.materiatypeId = null;
      this.queryParams.materiatypePid = null;
      if (data.level == 0) {
        this.getList()
        return
      }
      if (data.level == 1) {
        this.queryParams.materiatypePid = data.materiatypeId;
        console.log('pid', data.materiatypePid)
      } else {
        this.queryParams.materiatypeId = data.materiatypeId;
        console.log('id', data.materiatypeId)
      }

      this.getList()
    },
  }
};
</script>
